package com.thinkersre.service;

import com.thinkersre.dao.CommentMapper;
import com.thinkersre.entity.Comment;
import com.thinkersre.entity.DiscussPost;
import com.thinkersre.entity.Page;
import com.thinkersre.util.SensitiveFilter;
import com.thinkersre.util.ThinkersReConstant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CommentService implements ThinkersReConstant {

    @Resource
    private CommentMapper commentMapper;
    @Resource
    private SensitiveFilter sensitiveFilter;
    @Resource
    private DiscussPostService discussPostService;

    public List<Comment> findCommentsByEntity(int entityType,int entityId,int offset,int pageSize){
        return commentMapper.selectCommentsByEntity(entityType,entityId,offset,pageSize);
    }
    public int findCommentCount(int entityType , int entityId){
        return commentMapper.selectCountByEntity(entityType,entityId);
    }
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if (comment==null){
            throw new IllegalArgumentException("参数不能为空");
        }
        //添加评论
        //html编码转义
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        //自定义过滤
        comment.setContent(sensitiveFilter.Filter(comment.getContent()));
        int rowsTotal = commentMapper.insertComment(comment);
        //更新帖子评论数量
        if(comment.getEntityType() == ENTITY_TYPE_POST){
            int count = commentMapper.selectCountByEntity(comment.getEntityType(),comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(),count);
        }

        return rowsTotal;
    }
    public Comment findCommentById(int id){
        return commentMapper.selectCommentById(id);
    }


    /**
     * 查询我的回复
     **/
    public List<Comment> findCommentsByUserId(int userId, int entityType, int offset, int limit) {
        return commentMapper.selectCommentsByUserId(userId, entityType, offset, limit);
    }

    public int findCommentCountByUserId(int userId, int entityType) {
        return commentMapper.selectCountByUserId(userId, entityType);
    }
}
